<script>
	// 站点配置文件
	import siteinfo from './common.js';
	// 工具类
	import util from './utils/util.js';
	export default {
		data() {
			return {};
		},
		globalData: {
			api_root: siteinfo.ServerApi + 'index.php?s=/api/',
			api_static: siteinfo.ServerApi + 'static/',
			site_id: siteinfo.ServerSiteid, //站点ID
			site_type: siteinfo.site_type, //站点ID
			getToken() {
				return uni.getStorageSync('token');
			},
			getUserId() {
				return uni.getStorageSync('user_id');
			},
			getUserInfo() {
				return uni.getStorageSync('userInfo');
			},
			getUserMobile() {
				return uni.getStorageSync('mobile');
			},
			/**
			 * 显示成功提示框
			 */
			showSuccess(msg, callback) {
				uni.showToast({
					title: msg,
					icon: 'success',
					mask: true,
					duration: 1500,
					success() {
						if (callback) {
							setTimeout(() => {
								callback();
							}, 1500);
						}
					}
				});
			},
			/**
			 * 显示失败提示框
			 */
			showError(msg, callback) {
				uni.showModal({
					title: '友情提示',
					content: msg,
					showCancel: false,
					success(res) {
						if (callback) {
							callback();
						}
					}
				});
			},
			/**
			 * 检查登陆
			 */
			check_user() {
				let _this = this;
				var token = uni.getStorageSync('token');
				return new Promise(function(resolve, reject) {
					uni.request({
						url: _this.api_root + 'User/detail',
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							site_id: _this.site_id,
							site_type: _this.site_type,
							token: token
						},
						success(res) {
							if (res.statusCode !== 200 || typeof res.data !== 'object') {
								_this.showError('数据接口服务中断,请重新打开小程序');
								return false;
							}
							//接口授权失败,清空缓存（可能会存在与服务端缓存数据不一致）
							if (res.data.code === 0 || res.data.code === -1) {
								uni.clearStorageSync();
								resolve(res);
								return false;
							}
							uni.setStorageSync('user_id', res.data.data.userInfo.user_id);
							uni.setStorageSync('mobile', res.data.data.userInfo.mobile);
							uni.setStorageSync('userInfo', res.data.data.userInfo);
							//回调
							resolve(res);
						},
						fail(res) {},
						complete(res) {}
					});
				});
			},

			/**
			 * 授权登陆
			 */
			userlogin() {
				let _this = this;
				var str = _this.site_type;
				var loginType = str.replace("mp-", "");
				return new Promise(function(resolve, reject) {
					uni.login({
						provider: loginType,
						scopes: "auth_base", //静默登陆
						success: (result) => {
							uni.request({
								url: _this.api_root + 'user/login',
								data: {
									code: result.code,
									site_type: _this.site_type,
									site_id: _this.site_id
								},
								header: {
									'content-type': 'application/x-www-form-urlencoded'
								},
								method: 'POST',
								success: (res) => {
									if (res.statusCode !== 200 || typeof res.data !==
										'object') {
										_this.showError('小程序接口异常，请联系管理员处理');
										return false;
									}
									//接口授权失败
									if (res.data.code === 0 || res.data.code === -1) {
										_this.showError('接口返回异常，请检查！');
										return false;
									}
									uni.setStorageSync('token', res.data.data.token);
									uni.setStorageSync('user_id', res.data.data.user_id);
									uni.setStorageSync('mobile', res.data.data.mobile);
									//回调
									resolve(res);
								},
								fail: (err) => {
									// 需要的话请求失败处也可以使用回调
									_this.showError('小程序接口异常，请联系管理员处理');
									return false;
								}
							});
						}
					});
				});
			},

			/**
			 * 发起微信支付
			 */
			wxPayment(option) {
				let options = Object.assign({
					payment: {},
					success: () => {},
					fail: () => {},
					complete: () => {},
				}, option);
				wx.requestPayment({
					timeStamp: options.payment.timeStamp,
					nonceStr: options.payment.nonceStr,
					package: 'prepay_id=' + options.payment.prepay_id,
					signType: 'MD5',
					paySign: options.payment.paySign,
					success(res) {
						options.success(res);
					},
					fail(res) {
						options.fail(res);
					},
					complete(res) {
						options.complete(res);
					}
				});
			},
			/**
			 * get请求
			 */
			_get(url, data, success, fail, complete, check_login) {
				uni.showNavigationBarLoading();
				let _this = this;
				// 构造请求参数
				data = data || {};
				data.site_id = _this.site_id;
				data.site_type = _this.site_type;
				// 构造get请求
				let request = () => {
					data.token = uni.getStorageSync('token');
					uni.request({
						url: _this.api_root + url,
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						data: data,
						success(res) {
							if (res.statusCode !== 200 || typeof res.data !== 'object') {
								_this.showError('网络故障');
								return false;
							}
							if (res.data.code === 0) {
								// _this.showError(res.data.msg, () => {
								// 	if (fail) {
								// 		fail(res);
								// 	}
								// });
								// return false;
							} else {
								if (success) {
									success(res.data);
								}
							}
						},
						fail(res) {
							_this.showError(res.errMsg, () => {
								if (fail) {
									fail(res);
								}
							});
						},
						complete(res) {
							uni.hideNavigationBarLoading();
							if (complete) {
								complete(res);
							}
						}
					});
				};
				// 判断是否需要验证登录
				request();
			},

			/**
			 * post提交
			 */
			_post_form(url, data, success, fail, complete, isShowNavBarLoading) {
				let _this = this;
				isShowNavBarLoading || true;
				data.site_id = _this.site_id;
				data.site_type = _this.site_type;
				data.token = uni.getStorageSync('token');
				// 在当前页面显示导航条加载动画
				if (isShowNavBarLoading == true) {
					uni.showNavigationBarLoading();
				}
				uni.request({
					url: _this.api_root + url,
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					method: 'POST',
					data: data,
					success(res) {
						if (res.statusCode !== 200 || typeof res.data !== 'object') {
							_this.showError('网络故障');
							return false;
						}
						if (res.data.code === 0) {
							// _this.showError(res.data.msg, () => {
							// 	if (fail) {
							// 		fail(res);
							// 	}
							// });
							// return false;
						}
						if (success) {
							success(res.data);
						}
					},
					fail(res) {
						_this.showError(res.errMsg, () => {
							if (fail) {
								fail(res);
							}
						});
					},
					complete(res) {
						uni.hideNavigationBarLoading();
						if (complete) {
							complete(res);
						}
					}
				});
			},
			//获取场景值(scene)
			getSceneData(query) {
				return query.query.scene ? util.scene_decode(query.query.scene) : {};
			},
			getSceneDataIndex(query) {
				return query ? util.scene_decode(query) : {};
			},
		},
		/**
		 * 生命周期函数--监听小程序初始化
		 */
		async onLaunch(e) {
			let _this = this;
			// debugger
			_this.globalData.getSceneData(e)
			console.log(_this.globalData.getSceneData(e))
			if (!_this.globalData.getToken()) {
				var res = await _this.globalData.userlogin();
				try {
					_this.$isResolve();
				} catch (e) {
					console.error(e)
				}
			} else {
				//存在token,检查用户更新
				var check_user = await _this.globalData.check_user();
				if (check_user.data.code === 0 || check_user.data.code === -1) {
					//获取不了用户，去重新授权
					var res = await _this.globalData.userlogin();
					try {
						_this.$isResolve();
					} catch (e) {
						console.error(e)
					}
				} else {
					_this.$isResolve();
				}
			}
		},

		/**
		 * 当小程序启动，或从后台进入前台显示，会触发 onShow
		 */
		onShow(options) {
			let App = this;
		}
	};
</script>
<style>
	/* 加载核心样式 非 nvue 平台  */
	/* #ifndef APP-PLUS-NVUE */
	@import "./graceUI/graceUI.css";
	@import "./graceUI/graceIcons.css";
	/* #endif */

	/* 加载核心样式 nvue 平台  */
	/* #ifdef APP-PLUS-NVUE */
	@import "./graceUI/graceWeex.css";

	.grace-icons {
		font-family: graceIconfont;
	}

	/* #endif */
	.color-black {
		color: #333333;
	}

	.color-red {
		color: #FF0036;
	}

	.grace-title {
		color: #333333;
	}

	/* #ifndef APP-PLUS-NVUE */
	navigator {
		opacity: 1;
		background: none;
	}

	.navigator-hover {
		background: none;
		opacity: 0.8;
	}

	/* #endif */
</style>